package com.onenine.app.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.sdk.android.manager.OssManager;
import com.google.android.flexbox.FlexboxLayout;
import com.onenine.app.R;
import com.onenine.app.event.RefreshEvent;
import com.onenine.app.fragment.MineFragment;
import com.onenine.app.request.HeadPicSubmitRequest;
import com.onenine.app.request.RelationRequest;
import com.onenine.app.response.TargetUserInfoResponse;
import com.onenine.app.utils.CHelper;
import com.onenine.app.utils.DataType;
import com.onenine.app.utils.GlideUtils;
import com.onenine.app.utils.RoleResLoader;
import com.onenine.app.utils.UrlConfig;
import com.onenine.app.view.pulltozoomview.PullToZoomBase;
import com.onenine.app.view.pulltozoomview.PullToZoomScrollViewEx;
import com.onenine.base.base.BaseEventActivity;
import com.onenine.base.okhttp.BaseResponse;
import com.onenine.base.okhttp.OkCallback;
import com.onenine.base.okhttp.OkRequest;
import com.onenine.base.utils.AppConfig;
import com.onenine.base.utils.StatusBarUtils;
import com.onenine.base.utils.Toasty;
import com.onenine.base.view.CircleIndicatorView;
import com.onenine.base.view.NiceImageView;
import com.onenine.chat.rongcloud.RcUser;
import com.onenine.chat.rongcloud.UserCacheMgr;
import com.onenine.common.util.ApUtils;
import com.onenine.common.util.Logger;
import com.onenine.common.util.SizeUtils;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * 个人中心-我的
 */
public class UserDetailActivity extends BaseEventActivity implements View.OnClickListener, ViewPager.OnPageChangeListener
        , PullToZoomBase.OnPullZoomListener, OnBannerListener, EasyPermissions.PermissionCallbacks, OssManager.Callback, PullToZoomScrollViewEx.OnScrollYChangedListener {

    private static final String[] CAMERA_PERMISSIONS = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
    protected static final int REQ_OPEN_CAMERA = 189;
    private TextView mTvName, mTvAge, mTvHometown, mTvNetStatus, mTvSpecialSign;
    private Banner mBanner;
    private NiceImageView mImgAvatar;
    private FlexboxLayout mFbLabel, mFbObject, mFbHobby;
    private PullToZoomScrollViewEx mPullScrollView;
    private View mZoomImg, mTitleBar;
    private CircleIndicatorView mIndicatorView;
    private ImageButton mBtnDynamic;
    private ArrayList<String> mImgList = new ArrayList<>();
    private String mUserId, mCoverUrl;
    private ImageButton mBtnAttention;
    private int mHeadViewHeight;
    private boolean mBlnAttention;

    /**
     * 加载Activity
     *
     * @param context
     * @param userId
     */
    public static void launchActivity(Context context, String userId) {
        Intent intent = new Intent(context, UserDetailActivity.class);
        intent.putExtra("userId", userId);
        context.startActivity(intent);
    }

    /**
     * 加载新任务Activity
     *
     * @param context
     * @param userId
     */
    public static void launchNewTaskActivity(Context context, String userId) {
        Intent intent = new Intent(context, UserDetailActivity.class);
        intent.putExtra("userId", userId);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT);
        context.startActivity(intent);
    }

    @Override
    protected void setStatusBarStyle() {
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_user_detail;
    }

    @Override
    protected void initViews() {
        super.initViews();
        mUserId = getIntent().getStringExtra("userId");
        LayoutInflater layoutInflater = LayoutInflater.from(this);
        mPullScrollView = findViewById(R.id.sv_pull_to);
        View vHead = layoutInflater.inflate(R.layout.layout_mine_head, null, false);
        View vContent = layoutInflater.inflate(R.layout.layout_user_detail_content, null, false);
        mZoomImg = layoutInflater.inflate(R.layout.layout_mine_zoom_img, null, false);
        mPullScrollView.setHeaderView(vHead);
        mPullScrollView.setZoomView(mZoomImg);
        mPullScrollView.setScrollContentView(vContent);
        mHeadViewHeight = getResources().getDimensionPixelOffset(R.dimen.mine_album_banner_height);
        mIndicatorView = vHead.findViewById(R.id.civ_indicator);
        RelativeLayout.LayoutParams headParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, mHeadViewHeight);
        mPullScrollView.setHeaderLayoutParams(headParams);
        RelativeLayout.LayoutParams covParams = (RelativeLayout.LayoutParams) vContent.getLayoutParams();
        covParams.topMargin = getResources().getDimensionPixelOffset(R.dimen.mine_content_top_margin);
        mPullScrollView.setContentLayoutParams(covParams);
        mImgAvatar = vContent.findViewById(R.id.iv_headpic);
        mTvName = vContent.findViewById(R.id.tv_name);
        mTvAge = vContent.findViewById(R.id.tv_age);
        mTvNetStatus = vContent.findViewById(R.id.tv_net_status);
        mTvHometown = vContent.findViewById(R.id.tv_hometown);
        mTvSpecialSign = vContent.findViewById(R.id.tv_special_sign);
        mFbLabel = vContent.findViewById(R.id.fb_my_label);
        mFbObject = vContent.findViewById(R.id.fb_my_object);
        mFbHobby = vContent.findViewById(R.id.fb_my_hobby);
        mBtnDynamic = vContent.findViewById(R.id.btn_my_dynamic);
        mBanner = vHead.findViewById(R.id.banner);
        mBanner.setImageLoader(new GlideImageLoader());
        mBtnAttention = findViewById(R.id.btn_attention);
        mTitleBar = findViewById(R.id.vw_title_bar);
        StatusBarUtils.setTransparentForImageView(this, null);
    }

    @Override
    public void onStart() {
        super.onStart();
        mBanner.startAutoPlay();
    }

    @Override
    public void onStop() {
        super.onStop();
        mBanner.stopAutoPlay();
    }

    @Override
    protected void initListeners() {
        super.initListeners();
        mBtnDynamic.setOnClickListener(this);
        mBanner.setOnBannerListener(this);
        mBanner.setOnPageChangeListener(this);
        mImgAvatar.setOnClickListener(this);
        mTitleBar.setOnClickListener(this);
        mPullScrollView.setOnPullZoomListener(this);
        mPullScrollView.setOnScrollYChangedListener(this);
        mBtnAttention.setOnClickListener(this);
        findViewById(R.id.btn_back).setOnClickListener(this);
        findViewById(R.id.btn_greet).setOnClickListener(this);
        findViewById(R.id.btn_gift).setOnClickListener(this);
    }

    @Override
    public void initData() {
        super.initData();
        clearUserCache();
        getPersonalInfo();
    }

    /**
     * 清除该用户缓存信息
     */
    private void clearUserCache() {
        if (mUserId != null) {
            UserCacheMgr.getInstance().deleteUserCacheByUserId(mUserId);
        }
    }

    /**
     * 获取当前用户信息
     */
    private void getPersonalInfo() {
        OkRequest.getInstance().withUrl(UrlConfig.TARGET_USER_DETAIL)
                .withRequest(new RelationRequest(RcUser.getInstance().getUserId(), mUserId))
                .doRequest(MineFragment.class.getSimpleName(), new OkCallback<TargetUserInfoResponse>() {
                    @Override
                    public void onResponse(TargetUserInfoResponse response, String srcData) {
                        if (response.isSuccess()) {
                            showBackground(response.getBackgroundPicture(), response.getSex());
                            startImageBanner(response.getAlbum());
                            showInfoView(response);
                            showLabels(response);
                        }
                    }
                });
    }

    /**
     * 显示背景
     *
     * @param pic
     * @param sex
     */
    private void showBackground(String pic, int sex) {
        mCoverUrl = pic;
        mTitleBar.setBackgroundColor(RoleResLoader
                .getRoleColorResourceId(RoleResLoader.DynamicResName.THEME_COLOR, sex));
    }

    /**
     * 显示个人资料详情
     *
     * @param response
     */
    private void showInfoView(TargetUserInfoResponse response) {
        final int avatarSize = ApUtils.getApp().getResources().getDimensionPixelSize(R.dimen.avatar_size_62dp);
        final int avatarSizeSmall = ApUtils.getApp().getResources().getDimensionPixelSize(R.dimen.avatar_size_40dp);
        final String avatarUrl = CHelper.getOssThumbImageUrl(response.getPhoto(), avatarSize);
        mImgAvatar.setTag(R.id.data_tag, avatarUrl);
        GlideUtils.loadSrcImage(ApUtils.getApp(), mImgAvatar, avatarUrl);
        mTvName.setText(response.getNickName());
        mTvHometown.setText(response.getProvinceName() + " " + response.getCityName());
        mBtnDynamic.setImageResource(RoleResLoader.getRoleDrawableResourceId(RoleResLoader.DynamicResName.IC_M_DYNAMIC, response.getSex()));
        if ("".equals(response.getPersonSign())) {
            mTvSpecialSign.setHint(R.string.no_special_sign_default);
        } else {
            mTvSpecialSign.setText(response.getPersonSign());
        }
        if (response.isBlnOnline()) {
            //在线
            mTvNetStatus.setText(R.string.online);
            mTvNetStatus.setBackgroundResource(R.drawable.shape_online_corner_bg);
        } else {
            //离线
            mTvNetStatus.setText(R.string.offline);
            mTvNetStatus.setBackgroundResource(R.drawable.shape_offline_corner_bg);
        }
        mTvAge.setVisibility(View.VISIBLE);
        mTvAge.setCompoundDrawablesWithIntrinsicBounds(RoleResLoader
                .getRoleDrawableResourceId(RoleResLoader.DynamicResName.IC_SEX_WHITE), 0, 0, 0);
        mTvAge.setBackgroundResource(RoleResLoader.getRoleDrawableResourceId(RoleResLoader.DynamicResName.SHAPE_MINE_SEX_AGE_BG));
        mTvAge.setText(response.getAge() + "");
        mBtnAttention.setImageResource(RoleResLoader
                .getRoleDrawableResourceId(RoleResLoader.DynamicResName.SELECTOR_UD_ATTENTION_BG, response.getSex()));
        View vGiftGreet = findViewById(R.id.ll_greet_gift);
        vGiftGreet.setBackgroundResource(RoleResLoader.getRoleDrawableResourceId(RoleResLoader
                .DynamicResName.THEME_GRADIENT_CORNER_BG, response.getSex()));
    }

    /**
     * 显示标签组
     *
     * @param response
     */
    private void showLabels(TargetUserInfoResponse response) {
        showLabelView(mFbLabel, response.getMylabelNames());
        showLabelView(mFbObject, response.getIdealObjectLabelNames());
        showLabelView(mFbHobby, response.getUniqueHobbyLabelNames());
    }

    /**
     * 启动头像加相册banner
     *
     * @param albumStr
     */
    private void startImageBanner(String albumStr) {
        if (mBanner != null) {
            mBanner.releaseBanner();
            mBanner.stopAutoPlay();
        }
        mImgList.clear();
        if (!TextUtils.isEmpty(albumStr)) {
            String[] albums = albumStr.split(",");
            for (String album : albums) {
                mImgList.add(album);
            }
        }
        mBanner.setImages(mImgList);
        mBanner.start();
        if (mImgList.size() > 1) {
            mIndicatorView.playTo(mImgList.size(), 0);
            mIndicatorView.setVisibility(View.VISIBLE);
        } else {
            mIndicatorView.setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_back:
                finish();
                break;
            case R.id.btn_my_dynamic:
                DynamicListActivity.launchActivity(this, mUserId, mCoverUrl);
                break;
            case R.id.btn_greet:
                if (TextUtils.equals(mUserId, RcUser.getInstance().getUserId())) {
                    Toasty.showNormal(R.string.cant_operate_myself);
                    return;
                }
                PrivateMessageActivity.launchActivity(this
                        , mUserId, mTvName.getText().toString());
                break;
            case R.id.btn_attention:
                if (TextUtils.equals(mUserId, RcUser.getInstance().getUserId())) {
                    Toasty.showNormal(R.string.cant_operate_myself);
                    return;
                }
                doAttention();
                break;
            case R.id.btn_gift:
                if (TextUtils.equals(mUserId, RcUser.getInstance().getUserId())) {
                    Toasty.showNormal(R.string.cant_operate_myself);
                    return;
                }
                PrivateMessageActivity.launchActivity(this
                        , mUserId, mTvName.getText().toString(), true);
                break;
            case R.id.iv_headpic:
                if (mImgAvatar.getTag(R.id.data_tag) != null) {
                    BrowserImageActivity.launchActivity(this
                            , mImgAvatar.getTag(R.id.data_tag).toString());
                }
        }
    }

    /**
     * 关注或取消
     */
    private void doAttention() {
        OkRequest.getInstance().withUrl(mBlnAttention ? UrlConfig.CANCEL_ATTENTION : UrlConfig.ADD_ATTENTION)
                .withRequest(new RelationRequest(RcUser.getInstance().getUserId(), mUserId))
                .doRequest(PrivateMessageActivity.class.getSimpleName(), new OkCallback<BaseResponse>() {
                    @Override
                    public void onResponse(BaseResponse response, String srcData) {
                        if (response.isSuccess()) {
                            setButtonAttentionTxt(!mBlnAttention);
                            Toasty.showNormal(mBlnAttention
                                    ? R.string.attentioned : R.string.unAttentioned);
                        } else {
                            Toasty.showNormal(response.getMessage());
                        }
                    }
                });
    }

    /**
     * 设置关注按钮
     *
     * @param blnAttention
     */
    private void setButtonAttentionTxt(boolean blnAttention) {
        mBlnAttention = blnAttention;
        mBtnAttention.setSelected(blnAttention);
    }

    /**
     * 准备加载相册
     */
    protected void launchAlbum() {
        int size = AppConfig.SCREEN_WIDTH / 3 - SizeUtils.dp2px(10);
        Matisse.from(this)
                .choose(MimeType.ofImage())//显示照片
                .countable(false)//无序选择图片
                .capture(true)
                .captureStrategy(new CaptureStrategy(true
                        , ApUtils.getApp().getPackageName() + ".fileprovider"))
                .showSingleMediaType(true)//只显示一种媒体类型，此处只会显示图片，过滤了视频
                .maxSelectable(1)//最大选择数量为1
                .gridExpectedSize(size)//图片显示表格的大小getResources()
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)//图像选择和预览活动所需的方向。
                .thumbnailScale(0.85f)//缩放比例
                .theme(R.style.Matisse_Light)//主题
                .imageEngine(new GlideEngine())//加载方式
                .forResult(101);//请求码
    }

    /**
     * 显示标签组
     *
     * @param flexboxLayout
     * @param labelNameStr
     */
    public void showLabelView(FlexboxLayout flexboxLayout, String labelNameStr) {
        if (TextUtils.isEmpty(labelNameStr)) {
            return;
        }
        String[] labels = labelNameStr.split(",");
        int labelMargin = SizeUtils.dp2px(5);
        flexboxLayout.removeAllViews();
        for (String label : labels) {
            TextView tvLabel = (TextView) getLayoutInflater().inflate(R.layout.layout_my_label_item, null, false);
            tvLabel.setText(label);
            tvLabel.setBackgroundResource(R.drawable.shape_mine_label_bg);
            tvLabel.setTextColor(ActivityCompat.getColor(this, R.color.c999));
            tvLabel.setTextSize(11);
            FlexboxLayout.LayoutParams layoutParams = new FlexboxLayout
                    .LayoutParams(FlexboxLayout.LayoutParams.WRAP_CONTENT, getResources().getDimensionPixelOffset(R.dimen.dp22));
            layoutParams.setMargins(labelMargin, labelMargin, labelMargin, labelMargin);
            flexboxLayout.addView(tvLabel, -1, layoutParams);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(RefreshEvent event) {
        if (event.type == DataType.REFRESH_USER_INFO) {
            getPersonalInfo();
        }
    }

    @Override
    public void OnBannerClick(int position) {
        BrowserImageActivity.launchActivity(this, mImgList, position);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 101) {
                compressImages(Matisse.obtainPathResult(data));
            }
        }
    }

    /**
     * 压缩图片在100kb左右
     *
     * @param images
     */
    private void compressImages(List<String> images) {
        Luban.with(this)
                .load(images).ignoreBy(100)
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onSuccess(File file) {
                        OssManager.getInstance(ApUtils.getApp())
                                .ossUpload(file.getPath(), UserDetailActivity.this);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }
                }).launch();
    }

    @Override
    public void onSuccess(String url) {
        HeadPicSubmitRequest request = new HeadPicSubmitRequest();
        request.setUserId(RcUser.getInstance().getUserId());
        request.setPhoto(url);
        OkRequest.getInstance().withUrl(UrlConfig.UPLOAD_HEADPIC).withRequest(request)
                .doRequest(getClass().getSimpleName(), new OkCallback<BaseResponse>() {
                    @Override
                    public void onResponse(BaseResponse response, String srcData) {
                        if (response.isSuccess()) {
                            UserCacheMgr.getInstance().deleteUserCacheByUserId(request.getUserId());
                            getPersonalInfo();
                        } else {
                            Toasty.showNormal(response.getMessage());
                        }
                    }
                });
    }

    @Override
    public void onProgress(float progress) {

    }

    @Override
    public void onFailure(int errorCode, String errorMsg) {
        Logger.e("头像上传失败：" + errorCode + "," + errorMsg);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        if (requestCode == REQ_OPEN_CAMERA
                && CAMERA_PERMISSIONS.length == perms.size()) {
            launchAlbum();
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).setTitle(getString(R.string.permission_apply))
                    .setRationale(getString(R.string.permission_refuse_always_hint)).build().show();
        } else if (requestCode == REQ_OPEN_CAMERA) {
            Toasty.showNormal(R.string.permission_camera_hint);
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        GlideUtils.loadSrcImage(ApUtils.getApp()
                , (ImageView) mZoomImg, mImgList.get(position));
        mIndicatorView.playTo(mImgList.size(), position);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void onPullZooming(int newScrollValue) {
        if (mImgList.isEmpty()) {
            return;
        }
        if (mBanner.getVisibility() == View.VISIBLE) {
            mBanner.stopAutoPlay();
            mBanner.releaseBanner();
            mBanner.setVisibility(View.GONE);
        }
    }

    @Override
    public void onPullZoomEnd() {

    }

    @Override
    public void onPullZoomFinish() {
        if (mImgList.isEmpty()) {
            return;
        }
        if (mBanner.getVisibility() != View.VISIBLE) {
            mBanner.setVisibility(View.VISIBLE);
            mBanner.startAutoPlay();
        }
    }

    @Override
    public void onScrollChanged(float scrollY) {
        float alpha = scrollY / mHeadViewHeight;
        if (alpha >= 0.8f) {
            mTitleBar.setAlpha(1.0f);
        } else {
            mTitleBar.setAlpha(0.0f);
        }
    }

    /**
     * 图片加载器
     */
    private class GlideImageLoader extends ImageLoader {

        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {
            GlideUtils.loadSrcImage(context, imageView, (String) path);
        }
    }

}
